const jwt = require('jsonwebtoken');

// JWT认证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
  
  if (!token) {
    return res.status(401).json({ error: { message: '访问令牌缺失' } });
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'yx-design-jwt-secret-key-2024');
    req.user = decoded;
    next();
  } catch (error) {
    console.error('Token验证失败:', error);
    return res.status(403).json({ error: { message: '访问令牌无效' } });
  }
};

// 严格JWT认证中间件（必须有有效token）
const requireAuth = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ error: { message: '访问令牌缺失' } });
  }
  
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'yx-design-jwt-secret-key-2024');
    req.user = decoded;
    next();
  } catch (error) {
    console.error('Token验证失败:', error);
    return res.status(403).json({ error: { message: '访问令牌无效' } });
  }
};

// 生成JWT token
const generateToken = (payload) => {
  return jwt.sign(
    payload, 
    process.env.JWT_SECRET || 'yx-design-jwt-secret-key-2024',
    { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
  );
};

module.exports = {
  authenticateToken,
  requireAuth,
  generateToken
};